/**
 * 业务表单基础的增、改
 */
import { getPrefixUrl, getDetail, getFormBuildConfig, add, update } from '@/views/youshuda/api/BaseApi'
//表单配置
import {
  formConf
} from '@/views/youshuda/components/FormBuild/generator/config'
import {generateSnowflakeId} from "@/views/youshuda/utils/CustomSnowflake";

export const TableDetailMixins = {
  components: {
    FormItem: () => import('@/views/youshuda/components/FormItem/index'),
    //表单配置展示组件
    DraggableItem: () => import('@/views/youshuda/components/FormBuild/generator/DraggableItem'),
    //搜索模块组件
    SearchModel: () => import('@/views/youshuda/components/SearchModel/index')
  },
  props: {
    id: {
      default: ''
    },
    //处理入口类型：业务表单处理（Form）、流程表单处理（Proc）
    enterType: {
      default: 'Form'
    },
    //当前操作请求URL前缀
    prefixUrl: {
      default: ''
    },
    //表单设计Key
    formBuildKey: {
      default: ''
    },
    //是否需要操作按钮
    needOperBtn: {
      default: true
    },
    //当前表单字段信息
    fieldInfo: {
      type: Array,
      default: []
    },
    //表单配置信息
    configParams: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
  },
  data() {
    return {
      // 字段信息
      init: {
        fieldInfo: []
      },
      // 表单参数
      form: {},
      // 标识进入页面是否加载完成
      isLoadFinish: false,
      //表单设计字段配置信息
      formBuildConfig: [],
      formConf,
      //对象中下拉框
      formDataOptions: {},
      // 标识提交按钮是否可用
      isSubmitForm: false,
      //新增还是编辑
      operType:'add',
      // 主子表时，关联字段
      foreignKey: '',
      // 加载图片
      loading: require('@/assets/images/loading.gif'),
      // 是否打开搜索框
      isOpenSearch:false,
      SearchModel: '',
      nowRenderKey: '' //重新渲染组件时唯一标识
    }
  },
  created() {
    this.loading = this.loading + '?' + Math.random()

    if (!this.strIsNotEmpty(this.prefixUrl)) {
      this.msgError("操作失败，当前模块请求地址为空")
      return;
    }
    //获取主子表关联字段
    if (this.configParams != null && this.configParams != undefined) {
      this.foreignKey=this.toCamelCase(this.configParams['foreignKey'])
    }
    /** 加载数据 **/
    this.initData()
  },
  methods: {
    /** 获取数据 */
    initData() {
      if (this.strIsNotEmpty(this.id)) {
        this.operType = 'edit'
      } else {
        this.operType = 'add'
      }
      /**
       * 判断新增/修改
       */
      if (this.operType == 'edit') {
        this.reset()
        getDetail(this.prefixUrl, this.id).then(res => {
          if (res.code == 200) {
            //表单数据
            this.form = res.data['data']
            //表单设计字段配置信息
            this.formBuildConfig = res.data['formBuildConfig']
            //当foreignKey不为空时，表示当前为子表的编辑/新增请求
            if (this.strIsNotEmpty(this.foreignKey)) {
              this.form[this.foreignKey] = this.configParams['$RecodeId'];
              this.form['foreignKey'] = this.foreignKey;
            }
            this.resetForm('form')
            // 切换加载效果
            this.closeLoad()
          } else {
            this.msgError(res.msg)
          }
        })
      } else {
        //获取表单设计配置信息
        getFormBuildConfig(this.formBuildKey).then(res => {
          if (res.code == 200) {
            //表单设计字段配置信息
            this.formBuildConfig = res.data
            //当表单未配置情况下，使用通用配置方式
            if (this.formBuildConfig.length <= 0) {
              this.reset()
            }
            //当foreignKey不为空时，表示当前为子表的编辑/新增请求
            if (this.strIsNotEmpty(this.foreignKey)) {
              this.form[this.foreignKey] = this.configParams['$RecodeId'];
              this.form['foreignKey'] = this.foreignKey;
            }
            //生成唯一标识，主要考虑用于子表
            if (!this.strIsNotEmpty(this.form['id'])) {
              this.form['id'] = this.generateSnowflakeId()
            }
          } else {
            this.msgError(res.msg)
          }
        })
      }
    },
    closeLoad() {
      var that = this
      // 标记页面已加载完成
      setTimeout(function() {
        that.isLoadFinish = true
      }, 800)
    },
    /** 同步数据 **/
    ItemValChange(data) {
      this.form[data.key] = data.val
    },
    /** 打开搜索模块对话框 **/
    openSearchModel(model){
      if(model!=undefined && model!=null && this.strIsNotEmpty(model['model'])){
        this.SearchModel=model['model']
        this.isOpenSearch=true
      }else{
        this.msgError('未配置搜索业务模块')
      }
    },
    /** 关闭搜索模块对话框 **/
    closeSearchModel(){
      this.isOpenSearch=false
    },
    /** 获取在搜索模块对话框选择的行数据 **/
    ChooseSearchModelData(rowData){
      if(rowData!=undefined && rowData!=null){
        this.nowRenderKey=this.generateSnowflakeId()
        let columns=this.init.fieldInfo
        if(columns!=undefined && columns!=null && columns.length>0){
          for(let i=0;i<columns.length;i++){
            let column=columns[i]
            if(column['columnName']!='id' && column['columnName']!='params'){
              column['fieldData']=rowData[column['columnName']]
              this.form[column['columnName']] = rowData[column['columnName']]
            }
          }
          this.init.fieldInfo=columns
        }else{
          Object.keys(this.form).forEach(key=>{
            if(key!='id' && key!='params'){
              this.form[key] = rowData[key]
            }
          })
        }
      }
      /** 关闭搜索模块对话框 **/
      this.closeSearchModel();
    },
    // 表单重置
    reset() {
      this.init.fieldInfo = JSON.parse(JSON.stringify(this.fieldInfo))
      this.init.fieldInfo.forEach((item, index) => {
        this.$set(this.init.fieldInfo[index], 'fieldData', null)
        // 表单数据置空
        this.form[item.columnName] = null
        //主子表数据赋值
        if (item.columnName==this.foreignKey) {
          this.form[item.columnName] = this.configParams['$RecodeId'];
          this.$set(this.init.fieldInfo[index], 'fieldData', this.configParams['$RecodeId']);
        }
      })
      this.resetForm('form')
    },
    /** 取消按钮 */
    cancel() {
      this.$emit('cancel')
    },
    /** 校验数据是否通过，并返回 **/
    formData() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit('subFormData', { 'valid': valid, 'data': this.form })
        } else {
          this.$emit('subFormData', { 'valid': valid, 'data': null })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      //禁用提交按钮
      this.isSubmitForm = true
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.enterType == 'Form') {
            /**
             * 业务表单处理
             */
            if (this.operType == 'edit') {
              update(this.prefixUrl, this.form).then(response => {
                this.msgSuccess('修改成功')
                this.$emit('cancel', { isRef: true })
              }).finally(() => {
                this.isSubmitForm = false
              })
            } else {
              add(this.prefixUrl, this.form).then(response => {
                this.msgSuccess('新增成功')
                this.$emit('cancel', { isRef: true })
              }).finally(() => {
                this.isSubmitForm = false
              })
            }
          } else {
            /**
             * 流程表单处理
             */
            //TODO 流程表单处理

          }
        } else {
          //解除禁用提交按钮
          this.isSubmitForm = false
        }
      })
    },

    /**
     * ==============================表单设计模式数据同步==============================
     */

    /**
     * 同步表单值
     **/
    changeFormData(item) {

      if (item == null || item == undefined) {
        return
      }
      this.$set(this.form, item.key, item.val)
      /**
       * 下拉框联动的情况
       */
      if (item['type'] === 'select') {
        this.getLinkVModelOption(item)
      }
    },
    changeFormDataOptions(item) {
      if (item == null || item == undefined) {
        return
      }
      this.$set(this.formDataOptions, item.key, item.val)
    },
    /**
     * 处理赋值
     * @param item
     */
    assignFormData(item) {

      if (item == null || item == undefined) {
        return
      }
      /**
       * 判断是否需要进行赋值到其他字段操作
       */
      if (item['isAssignOtherModel']) {
        var result = item.val
        if (item['assignType'] == 'append') {
          result = this.form[item.key] + item.val
        }
        //处理待赋值字段
        this.$set(this.form, item.key, result)

        for (var i = 0; i < this.formBuildConfig.length; i++) {
          if (item.key == this.formBuildConfig[i]['vModel']) {
            this.$set(this.formBuildConfig[i], 'defaultValue', result)
            break
          }
        }
      }
    },

    /**
     * 下拉框联动的情况，获取联动下拉框选项数据
     * 返回结构：[{label: "是", value: "0"}, {label: "否", value: "1"}]
     */
    getLinkVModelOption(obj) {
      let that = this
      //联动字段选项集合key
      let itemKey = obj['config']['linkVModel']
      //联动字段选项集合key
      let linkVModelOptionUrl = obj['config']['linkVModelOptionUrl']
      //联动请求方式
      let linkVModelOptionReqType = obj['config']['linkVModelOptionReqType']
      if (!this.strIsNotEmpty(linkVModelOptionUrl) || !this.strIsNotEmpty(linkVModelOptionReqType)) {
        return
      }
      //当下拉框未选择是，清空被联动的下拉框
      if (!this.strIsNotEmpty(obj['val'])) {
        that.dealLinkVModelOption(itemKey, [])
      } else {
        if (linkVModelOptionReqType.toUpperCase() == 'POST') {
          //POST方式
          //发送请求
          this.request({
            url: linkVModelOptionUrl,
            method: 'post',
            data: { 'dictType': obj['val'] }
          }).then(res => {
            that.dealLinkVModelOption(itemKey, res.data)
          })
        } else {
          //GET方式
          //发送请求
          this.request({
            url: linkVModelOptionUrl + '/' + obj['val'],
            method: 'get'
          }).then(res => {
            that.dealLinkVModelOption(itemKey, res.rows)
          })
        }
      }

    },
    /**
     * 处理被联动的下拉组件选择、值信息
     */
    dealLinkVModelOption(itemKey, optionData) {
      let that = this
      //重新赋值下拉选项
      that.$set(that.formDataOptions, itemKey, optionData)
      //重新赋值已选择下拉值
      let selectItem = ''
      for (let item of optionData) {
        if (that.formData[itemKey].indexOf(item['value']) > -1) {
          selectItem += item['value'] + ','
        }
      }
      if (this.strIsNotEmpty(selectItem)) {
        selectItem = selectItem.substr(0, selectItem.lastIndexOf(','))
      }
      that.$set(that.formData, itemKey, selectItem)
    },
    /**
     * 按钮触发处理
     */
    btnClickHander(obj) {
      if (this.strIsNotEmpty(obj)) {
        eval(obj)
      }
    }

  },
  watch: {
    form: {
      deep: true,
      handler() {
        this.init.fieldInfo.forEach((item, index) => {
          // 表单数据置空
          this.$set(this.init.fieldInfo[index], 'fieldData', this.form[item.columnName])
        })
      }
    }

  }
}
